package com.tanhua.server.service;

import com.tanhua.commons.pojo.IMessage;
import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.mongo.UserLocationDTO;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.*;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuyp
 * @date 2021/01/29
 */
@Service
public class TanhuaService {
    @Reference
    private RecommendUserApi recommendUserApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private UserLocationApi userLocationApi;
    @Reference
    private UserLikeApi userLikeApi;
    @Reference
    private FriendApi friendApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询当前用户的今日佳人信息
     * @return
     */
    public ResponseEntity todayBest() {
        //1. 获取当前用户
        Long userId = UserHolder.getUserId();

        //2. 调用api，查询给当前用户推荐的今日佳人
        RecommendUser maxScoreUser = recommendUserApi.findMaxScoreUser(userId);
        if (maxScoreUser == null) {
            //如果查询到推荐的用户，就设置一个默认值
            maxScoreUser = new RecommendUser();
            maxScoreUser.setToUserId(userId);
            maxScoreUser.setUserId(2L);
            maxScoreUser.setScore(95D);
        }

        //3. 调用api，从数据库里查询佳人的详细信息
        UserInfo userInfo = userInfoApi.findById(maxScoreUser.getUserId());

        //4. 构造返回值
        RecommendUserVO vo = new RecommendUserVO();
        BeanUtils.copyProperties(userInfo, vo);
        vo.setTags(userInfo.getTags().split(","));
        vo.setFateValue(maxScoreUser.getScore().intValue());

        return ResponseEntity.ok(vo);
    }

    /**
     * 查询推荐给当前用户的佳人列表
     * @param queryVO 搜索条件（目前只需要使用其中的page，pagesize）
     */
    public ResponseEntity findRecommendUserList(RecommendUserQueryVO queryVO) {
        //1. 获取当前用户
        User user = UserHolder.getUser();

        //2. 查询推荐给当前用户的佳人列表
        PageResult<RecommendUser> pageResult = recommendUserApi.findRecommendUserList(user.getId(), queryVO.getPage(), queryVO.getPagesize());
        List<RecommendUser> recommendUserList = pageResult.getItems();
        if (recommendUserList == null || recommendUserList.size() == 0) {
            //没有查询到给当前用户推荐的佳人列表，我们要提供一批默认值
            recommendUserList = new ArrayList<>();
            String ids = "1,2,3,4,5,6,7,8,9,10";
            for (String id : ids.split(",")) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.parseLong(id));
                recommendUser.setScore(95D);
                recommendUserList.add(recommendUser);
            }

            pageResult = new PageResult<>(10, queryVO.getPagesize(), 1, queryVO.getPage(), recommendUserList);
        }

        //3. 转换结果RecommendUserVO
        List<RecommendUserVO> voList = new ArrayList<>();
        for (RecommendUser recommendUser : recommendUserList) {
            RecommendUserVO vo = new RecommendUserVO();
            //查询推荐的用户信息详情
            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
            //封装vo对象
            BeanUtils.copyProperties(userInfo, vo);
            vo.setTags(userInfo.getTags().split(","));
            vo.setFateValue(recommendUser.getScore().intValue());

            voList.add(vo);
        }

        //4. 构造返回值
        PageResult<RecommendUserVO> voPageResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult, voPageResult);
        voPageResult.setItems(voList);

        return ResponseEntity.ok(voPageResult);
    }

    /**
     * 查询某一用户的详细信息
     * @param targetUserId 目标用户的id（佳人id）
     */
    public ResponseEntity findPersonalInfo(Long targetUserId) {
        //1. 查询目标用户的详细信息
        UserInfo userInfo = userInfoApi.findById(targetUserId);

        //2. 把结果转换成RecommendUserVO
        RecommendUserVO vo = new RecommendUserVO();
        BeanUtils.copyProperties(userInfo, vo);
        vo.setTags(userInfo.getTags().split(","));

        //3. 需要查询目标用户和当前用户的缘分值
        Integer score = recommendUserApi.findRecommendScore(targetUserId, UserHolder.getUserId());
        vo.setFateValue(score);

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findStrangerQuestions(Long targetUserId) {
        //1. 查询目标用户的陌生人问题
        Question question = questionApi.findByUserId(targetUserId);
        if (question == null) {
            return ResponseEntity.ok("你喜欢我吗？");
        }

        return ResponseEntity.ok(question.getTxt());
    }

    public ResponseEntity replyStrangerQuestions(Long targetUserId, String reply) {
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());
        Question question = questionApi.findByUserId(targetUserId);
        String questionTxt = question == null ? "你喜欢我吗？" : question.getTxt();

        //封装消息对象
        IMessage message = new IMessage();
        message.setUserId(UserHolder.getUserId().toString());
        message.setNickname(userInfo.getNickname());
        message.setStrangerQuestion(questionTxt);
        message.setReply(reply);

        //给对方回复信息
        huanXinTemplate.sendMsg(targetUserId.toString(), message);

        return ResponseEntity.ok(null);
    }

    /**
     * 搜索附近的人
     * @param gender 要搜索的性别
     * @param metre 搜索的范围半径，单位是：米
     */
    public ResponseEntity searchNear(String gender, Integer metre) {
        //1. 调用API，搜索附近的人
        List<UserLocationDTO> dtoList = userLocationApi.searchNear(UserHolder.getUserId(), metre);

        //2. 循环剔除一些数据
        List<NearUserVO> voList = new ArrayList<>();
        for (UserLocationDTO dto : dtoList) {
            //1. 剔除自己
            if (dto.getUserId().longValue() == UserHolder.getUserId()) {
                continue;
            }

            //2. 剔除性别不符合的
            UserInfo userInfo = userInfoApi.findById(dto.getUserId());
            if (!"".equals(gender) && !userInfo.getGender().equals(gender)) {
                continue;
            }

            //3. 添加到voList里
            NearUserVO vo = new NearUserVO();
            vo.setUserId(dto.getUserId());
            vo.setAvatar(userInfo.getAvatar());
            vo.setNickname(userInfo.getNickname());
            voList.add(vo);
        }

        return ResponseEntity.ok(voList);
    }

    /* * @Description: 查询左滑右滑
     * @Param: []
     * @return: org.springframework.http.ResponseEntity
     * @Date:2021/03/01 15:09
     */
    public ResponseEntity findcards() {
        //查询附近的人列表信息
        List<UserInfo> userList = userInfoApi.find();
        //转成vo对象
        List<UserInfoVO> voList = new ArrayList<>();
        String value = redisTemplate.opsForValue().get("LOVE" + UserHolder.getUserId());
        if (value == null) {
            value = "";
        }
        for (UserInfo userInfo : userList) {
            if (value.contains(userInfo.getId().toString())) {
                continue;
            }
            UserInfoVO vo = new UserInfoVO();
            BeanUtils.copyProperties(userInfo, vo);
            if (userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }
            voList.add(vo);
        }
        return ResponseEntity.ok(voList);
    }

    /**
     * 探花-喜欢
     * @param likeUserId
     * @return
     */
    public ResponseEntity love(Long likeUserId) {
        //判断是否互为好友关系
        UserLike userLike = userLikeApi.userList(UserHolder.getUserId(), likeUserId);
        if (userLike ==null) {
            userLikeApi.saveUserLike(UserHolder.getUserId(), likeUserId);
            String value = redisTemplate.opsForValue().get("LOVE" + UserHolder.getUserId());
            if (value == null) {
                value = "";
            }
            value = value + "," + likeUserId;
            redisTemplate.opsForValue().set("LOVE" + UserHolder.getUserId(), value);
        } else {
            //1. 删除单向的喜欢 targetId喜欢当前用户
            userLikeApi.remove(UserHolder.getUserId(),likeUserId);
            //2. 建立双向的好友关系
            friendApi.addFriend(UserHolder.getUserId(),likeUserId);
        }
        return ResponseEntity.ok(null);
    }

    /**
     * 探花-不喜欢
     * @param likeUserId
     * @return
     */
    public ResponseEntity unlove(Long likeUserId) {
        Long userId = UserHolder.getUserId();
        userLikeApi.remove(userId,likeUserId);
        String value = redisTemplate.opsForValue().get("LOVE" + userId);
        if (value == null) {
            value = "";
        }
        value += "," + likeUserId;
        redisTemplate.opsForValue().set("LOVE" + userId, value);
        return ResponseEntity.ok(null);
    }

}
